//
//  WKPusherManager.swift
//  商家端Swift
//
//  Created by 天下宅 on 2016/10/21.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import UIKit
import KeychainAccess
import SVProgressHUD
import SwiftyJSON
import UserNotifications
import Toast_Swift

enum WKPushType:String {
    case LogoOut = "pusherLogout"
    case NewOrder = "orderPusher"
    case ThisOrder = "orderDispatch"//指定配送员
    case systemMessage = "pusherMessage"

}

private let GTID = "7SbTPMJMpq72Xvxk4jx1o2"
private let GTKey = "BKw2H2yk7b6c83K7CEDLI7"
private let GTSecret = "YXZIrjhX4I7VVXm9oHN0k7"


private var onceToken = 0
private var _WKGTPusherManager = WKGTPusherManager()
class WKGTPusherManager: NSObject,GeTuiSdkDelegate,UNUserNotificationCenterDelegate {
    var _presentOrderID:UInt = 0
    var isBind = false
    
    var binding = false
    
    var pushKey:String
    {
        get{
            //得到唯一推送标识
            let WKTag = Keychain(service: Bundle.main.bundleIdentifier!)
            // 不用用户名做为key 存储在钥匙链上 返回的是可选
            var pushTag = WKTag["key"]
            if (pushTag == nil)
            {
                pushTag = NSUUID().uuidString
                pushTag = pushTag!.replacingOccurrences(of: "-", with: "")
                WKTag["key"] = pushTag
            }
            return pushTag!
        }
    }
    static let shard:WKGTPusherManager = {
        
        let p = WKGTPusherManager()
        p.firstLoad()
        return p
    
    }()
    
    
    
    func firstLoad()
    {
        NotificationCenter.default.addObserver(self, selector: #selector(wkQuit(noti:)), name: NSNotification.Name(rawValue: QUIT), object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(wkLoginSuccse(noti:)), name: NSNotification.Name(rawValue: LOGIN_SUCCESS), object: nil)
    }
    func  wkQuit(noti:NSNotification)  {
//        WKLocalDataManager.wksetObject(value: "", forKey: ACCOUNT)
        WKLocalDataManager.wksetObject(value: "", forKey: PASSWD)
        WKLocalDataManager.saveToLocal()
        
        isLogin = false
        WKMapManager.shard.stopLoction()

        if noti.object != nil
        {
            NetWorkingManager.logout("正在退出", block: {(state, data) in
                switch state
                {
                case .Faild(let msg):
                    UIApplication.shared.keyWindow?.wkMakeToastToCenter(message: msg)
                case .Success:


                    if let topVC = UIApplication.shared.keyWindow?.rootViewController
                    {
                        topVC.dismiss(animated: true, completion: {
                            if let msg = noti.userInfo{
                                UIApplication.shared.keyWindow?.wkMakeToastToCenter(message: msg["message"] as? String ?? "")
                            }
                        })
                    }
                }
            })
        }
        else
        {
            

            if let topVC = UIApplication.shared.keyWindow?.rootViewController
            {
                topVC.dismiss(animated: true, completion: {
                    if let msg = noti.userInfo{
                        UIApplication.shared.keyWindow?.wkMakeToastToCenter(message: msg["message"] as? String ?? "")
                    }
                })
            }
        }
        

    }

    
    
    func registerJPush() {
        GeTuiSdk.runBackgroundEnable(true)
        GeTuiSdk.setChannelId("iOS_AppStore")
        GeTuiSdk.start(withAppId: GTID, appKey: GTKey, appSecret: GTSecret, delegate: self);
        self.registerUserNotification()
    }
    
    
    func bindAlias() {
        print("检测绑定之前 pushKey=" + pushKey)
        if binding {
            print("已绑定")
            return
        }
        binding = true
        if !isBind
        {
            print("pushKey=" + pushKey)
            GeTuiSdk.bindAlias(pushKey, andSequenceNum: "nole")
        }
    }
    
    func unbindAlias()
    {
        GeTuiSdk.unbindAlias(pushKey, andSequenceNum: "nole")
    }
    
    func bindAliasFail()  {
        
        SVProgressHUD.dismiss()
        let actionSheetController: UIAlertController = UIAlertController(title: "重要提示", message:"尊敬的用户，您好，为保证推送消息及时送到请点击确定按钮", preferredStyle: .alert)
        //重复注册
        let takePictureAction: UIAlertAction = UIAlertAction(title: "确定", style: .default)
        { action -> Void in
            //延时 10秒注册
            let deadlineTime = DispatchTime.now() + .seconds(60)
            DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
                WKGTPusherManager.shard.bindAlias()
            }
        }
        actionSheetController.addAction(takePictureAction)
        
        
        let cancleAction: UIAlertAction = UIAlertAction(title: "取消", style: .default)
        { action -> Void in

        }
        actionSheetController.addAction(cancleAction)
        
        var vc = UIApplication.shared.keyWindow!.rootViewController!
        
        
        while (vc.presentedViewController != nil) {
            vc = vc.presentedViewController!
        }
        vc.present(actionSheetController, animated: true, completion: nil)
    }
    
    /** 注册用户通知(推送) */
    func registerUserNotification() {
        
 
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [UNAuthorizationOptions.badge,UNAuthorizationOptions.sound,UNAuthorizationOptions.alert], completionHandler: { granted, error in
                if granted
                {
                    UIApplication.shared.registerForRemoteNotifications()
                    UNUserNotificationCenter.current().delegate = self
                }
            })
        } else {
            // Fallback on earlier versions
            UIApplication.shared.registerForRemoteNotifications()
            let userSettings = UIUserNotificationSettings.init(types: [UIUserNotificationType.alert,.sound,.alert], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(userSettings)
        }


    }
    
    
    func registerDeviceToken(deviceToken:Data) {
        
        var token = (deviceToken as NSData).description.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
        token = token.replacingOccurrences(of: " ", with: "")
        print("GTToken = " + token)
//        print(token)
//        print(deviceToken)

        GeTuiSdk.registerDeviceToken(token);
    }
    
    func handleRemoteNotification(userInfo: [AnyHashable : Any]) {
        GeTuiSdk.handleRemoteNotification(userInfo);
    }
    
    
    

    
    
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("iOS10 即将收到消息")
        completionHandler([UNNotificationPresentationOptions.badge,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.alert])
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("iOS10 收到消息")
        completionHandler()
    }
    
    
    
    // MARK: - GeTuiSdkDelegate
    
    
    func geTuiSdkDidAliasAction(_ action: String!, result isSuccess: Bool, sequenceNum aSn: String!, error aError: Error!) {
        
        let bindFlag = action == kGtResponseBindType
        
        var msg = bindFlag ? "绑定" : "解除绑定"
        msg += isSuccess ? "成功" : "失败"
        
//        print(msg)
        
        if action == kGtResponseBindType
        {
            binding = false
            isBind = isSuccess
            if !isBind
            {
                self.bindAliasFail()
            }
            else
            {
                WKLocalDataManager.wksetObject(value: pushKey, forKey: PUSH_KEY)//绑定成功 存本地
            }
        }
        else
        {
            if isSuccess
            {
                WKLocalDataManager.wkRemoveValua(forKey: PUSH_KEY)//解绑成功 删除本地
            }
        }
 


    }
    
    /** SDK启动成功返回cid */
    func geTuiSdkDidRegisterClient(_ clientId: String!) {
        // [4-EXT-1]: 个推SDK已注册，返回clientId
        print("个推注册成功" + clientId)
        print("检测绑定之前 pushKey=" + pushKey)

        if let cid = WKLocalDataManager.wkObjectForKey(key: PUSH_CID)
        {
            
            let cidStr = cid as! String
            if cidStr != clientId
            {
                //cid 改变
                WKLocalDataManager.wksetObject(value: cidStr, forKey: PUSH_CID)
                self.bindAlias()
            }
            else
            {
                let key = WKLocalDataManager.wkObjectForKey(key: PUSH_KEY)
                if key == nil
                {
                    self.bindAlias()
                }
            }
        }
        else
        {
            WKLocalDataManager.wksetObject(value: clientId, forKey: PUSH_CID)
            self.bindAlias()
        }
    }
    
    /** SDK遇到错误回调 */
    func geTuiSdkDidOccurError(_ error: Error!) {
        print("个推注册失败~\(error.localizedDescription)")
        // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    }
    
    /** SDK收到sendMessage消息回调 */
    func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
        // [4-EXT]:发送上行消息结果反馈
        let msg:String = "sendmessage=\(messageId),result=\(result)";
        print(msg)
    }

    func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
        var payloadMsg = "";
        if((payloadData) != nil) {
            payloadMsg = String.init(data: payloadData as Data, encoding: String.Encoding.utf8)!;
        }
        let msg:String = "Receive Payload: \(payloadMsg), taskId:\(taskId), messageId:\(msgId)";
        print(msg)
        self.handleMessage(message: payloadMsg);
    }
    
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }

    
    func handleMessage(message msg:String)
    {
        //未登录 或信息为空 不处理
        if !isLogin || msg == ""
        {
            return
        }
        
        let json = JSON.parse(msg)
        let type = json["type"].stringValue
        
        //未登录 不响应通知
        
        
        if type == WKPushType.LogoOut.rawValue
        {
            
            WKLocalDataManager.wksetObject(value: nil, forKey: PASSWD)
            WKLocalDataManager.wksetObject(value: nil, forKey: TOKEN)
            WKLocalDataManager.saveToLocal()
            print("接收到退出通知,开始退出")
            var userInfo = [AnyHashable : Any]()
            userInfo["message"] = "您的账户已在其他地方登陆"
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: QUIT), object: nil, userInfo: userInfo)
            
        }
        else if type == WKPushType.NewOrder.rawValue
        {
            //            self._presentOrderID
            WKAudioManager.sharedInstance.playNewOrder()
            if let topVC = UIApplication.shared.keyWindow?.rootViewController
            {
                
                if var vc = topVC.presentedViewController
                {
                    while (vc.presentedViewController != nil) {
                        vc = vc.presentedViewController!
                    }
                    
                    if vc.isKind(of: MainVC.classForCoder())
                    {
                        (vc as! MainVC).centerTVPresenter?.orderState = .new
                    }
                }
            }
        }
        else if type == WKPushType.ThisOrder.rawValue
        {
            WKAudioManager.sharedInstance.playThisOrder()
            if let topVC = UIApplication.shared.keyWindow?.rootViewController
            {
                
                if var vc = topVC.presentedViewController
                {
                    while (vc.presentedViewController != nil) {
                        vc = vc.presentedViewController!
                    }
                    
                    if vc.isKind(of: MainVC.classForCoder())
                    {
                        (vc as! MainVC).centerTVPresenter?.orderState = .my
                    }
                }
            }
        }
        else if type == WKPushType.systemMessage.rawValue
        {
            //弹出提示框?
            UIApplication.shared.keyWindow!.makeToast(json["content"].stringValue, duration: 2.5, position: .center, title: json["title"].stringValue, image: nil, style: nil, completion: nil)
            
        }
        else
        {
            UIApplication.shared.keyWindow!.makeToast(json["content"].stringValue, duration: 2.5, position: .center, title: json["title"].stringValue, image: nil, style: nil, completion: nil)
            //            UIApplication.shared.keyWindow!.makeToast(json["content"], duration: 2.5, position: .center, title: json["title"], image: nil, style: nil, completion: nil)
        }
    }
}




